from db import read_data, save_data


def show_product():
    init_product_dict = {}
    flag, product_dict = read_data(tag='product', path='product_data.json')
    init_product_dict.update(dict(enumerate(product_dict, 1)))
    for key, value in init_product_dict.items():
        print(
            f"{key} | {value} | 单价 : {product_dict[value]['product_price']} | 库存剩余 : {product_dict[value]['product_inventory']}")
        init_product_dict[key] = {'name': value, 'product_price': product_dict[value]['product_price'],
                                  'product_inventory': product_dict[value]['product_inventory']
                                  }
    return init_product_dict


def get_product_name():
    init_product_dict = show_product()
    product_choice = input("请输入商品编号 : ").strip()
    if not product_choice.isdigit():
        return False, "请输入数字！"
    product_choice = int(product_choice)
    if product_choice not in init_product_dict.keys():
        return False, "编号有误！"
    product_dict = init_product_dict[product_choice]
    return True, product_dict


def count_product_price(product, count=1):
    # 计算价钱
    flag, product_dict = read_data(tag='product', path='product_data.json')
    if product_dict[product]['product_inventory'] < count:
        return False, f"商品 {product} 数量不足！"
    balance = product_dict[product]['product_price'] * count
    return True, balance


def renew_product_interface(product, count=1):
    flag, product_dict = read_data(tag='product', path='product_data.json')
    product_dict[product]["product_inventory"] -= count
    flag, msg = save_data(tag='product', path='product_data.json', data=product_dict)
    if not flag:
        return msg
    return True, msg


def add_shop_cart():
    shopping_cart = {}
    while True:
        flag, product_dict = get_product_name()
        if not flag:
            return flag, product_dict
        if product_dict['name'] not in shopping_cart.keys():
            shopping_cart[product_dict['name']] = 1
        else:
            shopping_cart[product_dict['name']] += 1
        exit_cart = input("是否退出添加购物车,输入q退出:")
        if exit_cart == 'q':
            break
    return True, shopping_cart
